package cn.ac.iscas.action.paper;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.ac.iscas.action.project.ProjectQuery;
import cn.ac.iscas.bean.PageView;
import cn.ac.iscas.bean.paper.Paper;
import cn.ac.iscas.bean.project.Project;
import cn.ac.iscas.bean.project.ProjectDocument;
import cn.ac.iscas.service.paper.IPaperService;
import cn.ac.iscas.service.project.IProjectService;

@Controller @Scope("prototype")
public class ProjectBindAction {
	private Project project;
	private Paper paper;
	private String[] projectId;
	private ProjectQuery projectQuery;
	private int page;
	@Resource private IProjectService projectService;//运行时动态注入projectService层
	@Resource private IPaperService paperService;
	
	public String deleteProjectBind() throws IOException
	{
		System.out.println("bind");
		System.out.println("paperid"+paper.getId());
		System.out.println("project"+project.getId());
		paper = paperService.get(Paper.class, paper.getId());
		Set<Project> projects = paper.getProjects();
		project = projectService.get(Project.class, project.getId());
		projects.remove(project);
		paper.setProjects(projects);
		paperService.update(paper);
		ActionContext ctx = ActionContext.getContext();     
	    HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
	    response.setContentType("text/html;charset=utf-8");
	    PrintWriter out=response.getWriter();
	    response.setContentType("text/html;charset=utf-8");
	    out.println("成功删除");
		return null;
	}
	
	public String showProjct() throws IOException 
	{
		ActionContext ctx = ActionContext.getContext();     
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		//起始索引
		HttpServletRequest request = ServletActionContext.getRequest();
		int start = Integer.parseInt(request.getParameter("start"));
		//页大小
		int limit = Integer.parseInt(request.getParameter("limit"));
		System.out.println(start + "," + limit);
		//总记录条数，如果是数据库则要通过count 计算出来
		long totalProperty;
		page =start/limit+1;
		PageView<Project> pageView=new PageView<Project>(7,page);
		StringBuffer jpql = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("id", "desc");
		pageView.setQueryResult(projectService.getScrollData(Project.class,start, 
				limit, jpql.toString(), params.toArray(), orderby));
		totalProperty=pageView.getTotalrecord();
		String fmt = "{projectId: %d, name: '%s'}";
		StringBuffer s = new StringBuffer("{totalProperty:");
		s.append(totalProperty).append(", root:[");
		int i = 0;
	    for(Project project:pageView.getRecords())
	    {   
	    	s.append(String.format(fmt, project.getId(),"项目编号："+project.getProjectNo()+"    项目名称："+project.getProjectName()));
			if( i< pageView.getRecords().size() - 1){
			s.append(",");//各json对象用“,”隔开，最后一个不要
			i++;
			}
	    }
		s.append("]}");
		System.out.println(s.toString());
		out.println(s.toString());
		out.flush();
		out.close();
		return null;
	}
	public String showSelection()
	{
		if(page<=0)page=1;
		StringBuffer jpql = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		if(projectQuery!=null && projectQuery.getProjectNo()!=null && !"".equals(projectQuery.getProjectNo())){
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.projectNo = ?");
			params.add(projectQuery.getProjectNo());
		}
		if(projectQuery!=null && projectQuery.getProjectName()!=null && !"".equals(projectQuery.getProjectName())){
			if(params.size()>0) jpql.append(" and ");
			System.out.println(projectQuery.getProjectName()+"name");
			jpql.append(" o.projectName like ?");
			params.add("%"+ projectQuery.getProjectName()+ "%");
		}
		if(projectQuery!=null && projectQuery.getPersonInCharge()!=null && !"".equals(projectQuery.getPersonInCharge())){
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.personInCharge = ?");
			params.add(projectQuery.getPersonInCharge());
		}
		if(projectQuery!=null && projectQuery.getReposiblePerson()!=null && !"".equals(projectQuery.getReposiblePerson())){
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.reposiblePerson = ?");
			params.add(projectQuery.getReposiblePerson());
		}
		if(projectQuery!=null && projectQuery.getState()!=null &&!"".equals(projectQuery.getState()))
		{
			if(params.size()>0) jpql.append(" and ");
			jpql.append(" o.state = ?");
			params.add(projectQuery.getState());
		}
		PageView<Project> pageView=new PageView<Project>(7,page);
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("id", "desc");
		pageView.setQueryResult(projectService.getScrollData(Project.class,pageView.getFirstResult(), 
				pageView.getMaxresult(), jpql.toString(), params.toArray(), orderby));
		ActionContext.getContext().put("pageView", pageView);
		paper = paperService.get(Paper.class, paper.getId());
		ActionContext.getContext().put("paper",paper);
		Set<Project> projects = paperService.getProjects(Paper.class, paper.getId());
		ActionContext.getContext().put("selectedProjects", projects);
		return "selectView";
	}
	public String selectProject()
	{
		Set<Project> projects;
		paper = paperService.get(Paper.class, paper.getId());
		if(paper.getProjects()!=null)
	    {
	    	projects = paperService.getProjects(Paper.class, paper.getId());
	    }
	    else
	    {
	    	projects = new HashSet<Project>();
	    }
		if(projectId!=null)
		{
		    for(String id:projectId)
		    {
			    Project project = projectService.get(Project.class, Integer.valueOf(id));
			    projects.add(project);
		     }
		    paper.setProjects(projects);
		    paperService.update(paper);
		}
		return showSelection();
	}
	public Paper getPaper() {
		return paper;
	}
	public void setPaper(Paper paper) {
		this.paper = paper;
	}
	public IProjectService getProjectService() {
		return projectService;
	}
	public void setProjectService(IProjectService projectService) {
		this.projectService = projectService;
	}
	public IPaperService getPaperService() {
		return paperService;
	}
	public void setPaperService(IPaperService paperService) {
		this.paperService = paperService;
	}
	public void setProjectQuery(ProjectQuery projectQuery) {
		this.projectQuery = projectQuery;
	}
	public ProjectQuery getProjectQuery() {
		return projectQuery;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getPage() {
		return page;
	}
	public void setProjectId(String[] projectId) {
		this.projectId = projectId;
	}
	public String[] getProjectId() {
		return projectId;
	}
	public void setProject(Project project) {
		this.project = project;
	}
	public Project getProject() {
		return project;
	}
}
